/*
 * @Author: Clark
 * @Email: haixuanwoTxh@gmail.com
 * @Date: 2023-02-03 13:03:09
 * @LastEditors: Clark
 * @LastEditTime: 2023-02-03 22:34:38
 * @Description: file content
 */

#include "apue.h"
#include <sys/socket.h>

#define MAXSLEEP 128

int connect_retry(int domain, int type, int protocol, const struct sockaddr *addr, socklen_t alen)
{
    int sockfd = -1;

    // Try to connect with exponential banckoff
    for (int numsec = 0; numsec <= MAXSLEEP; numsec <<= 1)
    {
        if ((sockfd = socket(domain, type, protocol)) < 0)
        {
            return -1;
        }

        if (connect(sockfd, addr, alen) == 0)
        {
            // connect accepted
            return 0;
        }
        close(sockfd);

        // Delay before trying again
        if (numsec <= MAXSLEEP/2)
        {
            sleep(numsec);
        }
    }

    return -1;
}
